var selectedRow = null;
var selectedAppRow = null;
// 默认选中事件
var refresh =0;
// 选中
var selected = 0,hit  = 0;
//初始化编辑器
window.UEDITOR_CONFIG = {
    // 为编辑器实例添加一个路径，这个不能被注释
    UEDITOR_HOME_URL: basePath+"js/ueditor/",
    // 服务器统一请求接口路径
    serverUrl:basePath+ "ueditor/dispatch"
}
var ue = UE.getEditor('serviceContent', {
    initialFrameHeight:350,//编辑区域高度
    maximumWords:1024, autoHeightEnabled: false,
    autoFloatEnabled: true,allowDivTransToP: false,
    toolbars: [[
        'preview', //预览
        'source', //源代码
        'bold', //加粗
        'indent', //首行缩进
        'italic', //斜体meta
        'underline', //下划线
        'strikethrough', //删除线
        'subscript', //下标
        'fontborder', //字符边框
        'superscript', //上标
        'formatmatch', //格式刷
        'blockquote', //引用
        'pasteplain', //纯文本粘贴模式
        'horizontal', //分隔线
        'removeformat', //清除格式
        'time', //时间
        'date', //日期
        'link',
        'unlink', //取消链接
        'inserttitle', //插入标题
        // 'insertcode', //代码语言
        'fontfamily', //字体
        'fontsize', //字号
        // 'paragraph', //段落格式
        // 'emotion', //表情
        'spechars', //特殊字符
        'simpleupload', //单图上传
        'justifyleft', //居左对齐
        'justifyright', //居右对齐
        'justifycenter', //居中对齐
        'justifyjustify', //两端对齐
        'forecolor', //字体颜色
        'backcolor', //背景色
        // 'insertorderedlist', //有序列表
        // 'insertunorderedlist', //无序列表
        // 'directionalityltr', //从左向右输入
        // 'directionalityrtl', //从右向左输入
        'rowspacingtop', //段前距
        'rowspacingbottom', //段后距
        'imagenone', //默认
        'imageleft', //左浮动
        'imageright', //右浮动
        'imagecenter', //居中
        'lineheight', //行间距
        'edittip ', //编辑提示
        'customstyle', //自定义标题
        'autotypeset', //自动排版
        // 'help', //帮助
        'cleardoc', //清空文档
    ]]
});

//  加上分页上
$(function () {
    newCheck.initByName('del_text');
    selectedAppRow = searchInfo;
    // 名称是 编辑页面的时候需要的
    selectedAppRow.bizName = searchInfo.thirdBizName;
    selectedAppRow.orgName = searchInfo.thirdOrgName;
    selectedAppRow.docName = searchInfo.thirdDocName;
    selectedAppRow.isvName = searchInfo.thirdIsvName;
    // 新增的服务项的时候需要的
    selectedAppRow.sortNum = searchInfo.sortNum;
    selectedAppRow.bizCode = searchInfo.bizParentCode;
    $("#isvPid").val(selectedAppRow.isvPid);
    $("#refCode").val(selectedAppRow.refCode);
    $("#orgCode").val(selectedAppRow.orgCode);
    $("#bizParentCode").val(selectedAppRow.bizParentCode);
    $("#bizParentName").val(selectedAppRow.bizParentName);
    $("#ssortNum").val(selectedAppRow.sortNum);
    $("#thirdBizName").val(selectedAppRow.thirdBizName);
    $("#thirdOrgName").val(selectedAppRow.thirdOrgName);
    $("#thirdDocName").val(selectedAppRow.thirdDocName);
    $("#thirdIsvName").val(selectedAppRow.thirdIsvName);
    console.log(searchInfo);
    console.log(selectedAppRow);
});

function winHandleServerResult(res) {
    if(hit==0){
        if(res.list.length > 0)
            for(var i=0 ; i<res.list.length ;i++){
                // 加了分页一定能选中 二货一定要加分页也是醉了 下回别人我加回去
                if( res.list[i].appid == appid){
                    selectedAppRow =res.list[i];
                    $("#isvPid").val(selectedAppRow.isvPid);
                    $("#refCode").val(selectedAppRow.refCode);
                    $("#orgCode").val(selectedAppRow.orgCode);
                    $("#bizParentCode").val(selectedAppRow.bizCode);
                    $("#bizParentName").val(selectedAppRow.bizName);
                    $("#ssortNum").val(selectedAppRow.sortNum);
                    $("#thirdBizName").val(selectedAppRow.bizName);
                    $("#thirdOrgName").val(selectedAppRow.orgName);
                    $("#thirdDocName").val(selectedAppRow.docName);
                    $("#thirdIsvName").val(selectedAppRow.isvName);
                    hit = 1;
                }
            }
        doRefresh();
        refresh++;
    }
    return {
        "total": res.total,//总页数
        "rows": res.list   //数据
    };
}
var index = null;
function onceCheck(value,row,$elem){
    if(hit ==1 && row.appid == appid ){
        index =$elem;
        setTimeout(function(){
            $("#dataAppTable > tbody > tr[data-index='" +index+"']").addClass("success");
        },500);
        refresh ++;
    }
    return value;
}

$(function () {
    regValidate(["#_bizDataForm"]);
    window.actionEvents = {
        'click .infoView': function(e, value, row, index) {
            //编辑操作
            selectedRow = row;
            openEnumPage();
        },
    }
});

function doRefresh() {
    if($("#isvPid").val().length == 0){
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    selectedRow = null;
    $('#dataTable').bootstrapTable('refresh', {
        url: basePath + 'bizApp/getGridBizAppData?t=' + new Date().getTime(),
    });
}

function getParams(params) {
    var postData = {
        pageSize : params.pageSize,
        pageNo : params.pageNumber
    };
    postData.appCategory ='doctor';
    postData.isParent ='0';
    $("#searchForm").serializeArray().map((function (item,index,input) {
        postData[item.name] = item.value;
    }));
     postData.isvPid = $("#isvPid").val();
     postData.refCode = $("#refCode").val();
     postData.orgCode = $("#orgCode").val();
     postData.bizParentCode = $("#bizParentCode").val();
     postData.bizParentName = $("#bizParentName").val();
     selectedRow = null;
    return postData;
}


function doAppRefresh() {
    $('#dataAppTable').bootstrapTable('refresh', {
        url: basePath + 'bizApp/getGridBizAppData?t=' + new Date().getTime(),
    });
}

function getAppParams(params) {
    var  postData = {
        appCategory : 'doctor',
        isParent : '1',
        pageSize : params.pageSize,
        pageNo : params.pageNumber
    };
    postData[$("#search").attr("name")] = $("#search").val();
    // 没有点击 没有命中 的情况
    if( selected  || hit ){
        $("#isvPid").val("");
        $("#refCode").val("");
        $("#orgCode").val("");
    }
    return postData;
}


function getWinParams(params) {
    var  postData = {
        appCategory : 'doctor',
        pageSize : params.pageSize,
        pageNo : params.pageNumber
    };
    postData.isvPid = selectedAppRow.isvPid;
    postData.refCode = selectedAppRow.refCode;
    postData.bizCode = selectedAppRow.bizCode;
    postData.orgCode = selectedAppRow.orgCode;
    postData.bizName = $.trim($("#winBizName").val());
    return postData;
}
function doWinRefresh() {
    $('#WinTable').bootstrapTable('refresh', {
        url: basePath + 'bizApp/getGridBizDataChlid?t=' + new Date().getTime(),
    });
}



$("#dataAppTable").on("click-row.bs.table",function(e,row,ele){
    $("#dataAppTable .success").removeClass("success");
    $(ele).addClass("success");
    selectedAppRow = row;
    $("#isvPid").val(selectedAppRow.isvPid);
    $("#refCode").val(selectedAppRow.refCode);
    $("#orgCode").val(selectedAppRow.orgCode);
    $("#bizParentCode").val(selectedAppRow.bizCode);
    $("#bizParentName").val(selectedAppRow.bizName);
    $("#ssortNum").val(selectedAppRow.sortNum);
    $("#thirdBizName").val(selectedAppRow.bizName);
    $("#thirdOrgName").val(selectedAppRow.orgName);
    $("#thirdDocName").val(selectedAppRow.docName);
    $("#thirdIsvName").val(selectedAppRow.isvName);
    selected = 1 ;
    hit = 2;
    doRefresh();
});


var selcetIsv = null;

function formatStatus(value, row, index) {
    if (value == 'enabled') {
        return '有效';
    }
    if (value == 'disabled') {
        return '无效';
    }
    return value;
}

//右边选中事件
$("#dataTable").on("click-row.bs.table",function(e,row,ele){
    $("#dataTable .success").removeClass("success");
    $(ele).addClass("success");
    selectedRow = row;
});




function doSaveApp() {
    if(selectedAppRow == null){
        toastr.error("请选择服务机构");
        return;
    }
    var selectRows = getSelectedRows("#WinTable");
    if(selectRows == null || selectRows.length == 0){
        toastr.error("请选择服务项");
        return;
    }
    var list = new Array();
    for (var index in selectRows){
        list.push({refCode:selectedAppRow.refCode,sortNum:selectedAppRow.sortNum,bizCode:selectRows[index].bizCode,
            appName:selectRows[index].bizName,appDisplayName:selectRows[index].bizName,status:'publish',appCategory:'doctor'});
    }

    $.ajax({
        type: 'post',
        url: basePath + 'bizApp/addBizAppChlid',
        dataType: 'json',
        contentType: "application/json",
        beforeSend:function () {
            showLoading();
        },
        complete:function(){
            hideLoading();
        },
        data: JSON.stringify({isvPid:selectedAppRow.isvPid,orgCode:selectedAppRow.orgCode,
             appid:selectedAppRow.appid,refDataList:list,appCategory:'doctor'}),
        success : function (data) {
            if(data.result){
                toastr.success("服务项新增成功");
                doRefresh();
                $("#addBizApp").modal('hide');
            }else{
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });

}

/******************************************************************************************/
var VueObj = new Vue({
    el:"#VueObj",
    data:{addBizApp:{},editBizApp:[]}
});
function add() {
    if(selectedAppRow == null){
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    $("#winBizName").val("");
    VueObj.$set(VueObj.$data,"addBizApp",JSON.parse(JSON.stringify(selectedAppRow)));
    doWinRefresh();
   $("#addBizApp").modal(true);
};

function edit() {
    if(selectedRow == null){
       toastr.error(common_no_choose_msg.format("操作"));
       return;
    }
    VueObj.$set(VueObj.$data,"addBizApp",JSON.parse(JSON.stringify(selectedAppRow)));
    VueObj.$set(VueObj.$data,"editBizApp",JSON.parse(JSON.stringify(selectedRow)));
    ue.setContent(selectedRow.serviceContent);
    $("#editBizApp").modal(true);
}


function doEditBizApp() {
    if(selectedRow == null){
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    // if($.trim(ue.getContent()).length == 0){
    //     toastr.error("服务说明为必填");
    //     return;
    // }
    if($("#appType").val() == 'html' && $.trim($("#appLinkUrl").val()) == ''){
        toastr.error("h5地址为必填");
        return;
    }
    var postData = {};
    $("#editBizAppform").serializeArray().map((function (item,index,input) {
        postData[item.name] = item.value;
    }));
    postData.serviceContent = $.trim(ue.getContent());
    postData.id = selectedRow.id;
    postData.appid = selectedRow.appid;
    postData.isvPid = selectedRow.isvPid;
    postData.bizCode = selectedRow.bizCode;
    postData.orgCode = selectedRow.orgCode;
    postData.refCode = selectedRow.refCode;
    postData.appCategory = selectedRow.appCategory;
    postData.status =$("#status").val();
    postData.validDay = $.trim($("#validDay").val());
    postData.sortNum = $.trim($("#sortNum").val());
    $.ajax({
        type: 'post',
        url: basePath + 'bizApp/editBizAppChild',
        dataType: 'json',
        contentType: "application/json",
        beforeSend:function () {
            showLoading();
        },
        complete:function(){
            hideLoading();
        },
        data: JSON.stringify(postData),
        success : function (data) {
            if(data.result){
                toastr.success("服务项编辑成功");
                doRefresh();
                $("#editBizApp").modal('hide');
            }else{
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function dodel() {
    if(selectedRow == null){
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    $("input[name=del_text]").removeAttrs('checked');
    $("#del_textarea").val("");
    // if(selectedRow.dataStatus == 'pending_check'){
    //     toastr.error("这是待审核数据不能删除");
    //     return;
    // }
    // if(selectedRow.dataStatus == 'check_pass'){
    //     toastr.error("这是审核通过的数据请,先撤销再删除");
    //     return;
    // }
    $("#delAppWin").modal(true);
}


function dodelApp() {
    var result = new Array();
    $("input[name=del_text]:checked").each(function (index,value) {
        result.push($(value).val());
    });
    if(result.length==0 && $("#del_textarea").val() == ''){
        toastr.error("请选择撤销原因");
        return;
    }
    result.push($("#del_textarea").val());
    var postData = {};
    postData.id = selectedRow.id;
    postData.appid = selectedRow.appid;
    postData.isvPid = selectedRow.isvPid;
    postData.refCode = selectedRow.refCode;
    postData.orgCode = selectedRow.orgCode;
    postData.bizCode = selectedRow.bizCode;
    postData.appCategory = selectedRow.appCategory;
    postData.status = selectedRow.status;
    postData.dataStatus = 'delete';
    postData.remark = result.join(",");
    $.ajax({
        type: 'post',
        url: basePath + 'bizApp/delBizAppChild',
        dataType: 'json',
        contentType: "application/json",
        beforeSend:function () {
            showLoading();
        },
        complete:function(){
            hideLoading();
        },
        data: JSON.stringify(postData),
        success : function (data) {
            if(data.result){
                toastr.success(data.message);
                doRefresh();
                $("#delAppWin").modal('hide');
            }else{
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}


function doback() {
    console.log(searchStrAfter(searchStr));
    window.location.href = basePath+"bizApp/docPage?t="+new Date().getTime()+"&"+searchStrAfter(searchStr) +
    '&isOrgExist=' + 1 + '&isTeamExist=' + 1;
    // '&isOrgExist=' + searchInfo.isOrgExist + '&isTeamExist=' + searchInfo.isTeamExist;
}


/***************************************************************************************/
function selectType() {
  var selectType =  $("#selectType").val();
  switch (selectType){
      case 'orgName':
      {
          $("#search").attr("name",selectType);
          $("#search").attr("placeholder","输入机构名称");
          break;
      };
      case 'bizName':
      {
          $("#search").attr("name",selectType);
          $("#search").attr("placeholder","输入业务类型");
          break;
      };
      case 'isvName':
      {
          $("#search").attr("name",selectType);
          $("#search").attr("placeholder","输入服务商名称");
          break;
      };
  }
}

function formatterStatus(value,row,index) {
    if(statusEnum != null){
        return statusEnum[value];
    }
    console.log(row.appid);
    return "";
};


function doExport() {
    if($("#isvPid").val().length == 0){
        toastr.error(common_no_choose_msg.format("导出"));
        return;
    }
    $('#searchForm').attr("action",basePath+"bizApp/exportDocBizAppExcelChild");
    $('#searchForm').submit();
}


function onchangeh5(e) {
    if($(e).val() == 'html'){
        $("#h5").removeAttrs("hidden");
    }else{
        $("#h5").attr("hidden",'hidden');
    }
}


function edit2() {
    if(selectedRow == null){
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    // 左侧内容
    // 选中的appid
    // 选中的id
    // 第一个页面 查询参数
    // 第二个页面 查询参数
    var searchStr2 =  searchStrBefore("#searchForm")+",selectType="+$("#selectType").val()+",search2="+$("#search").val();
   var isTeamExist  ;
    if(searchInfo.isTeamExist && searchInfo.isTeamExist != "" && searchInfo.isTeamExist != "undefined" ){
        // isTeamExist = searchInfo.isTeamExist;
        searchStr2 +=",isTeamExist="+searchInfo.isTeamExist;
    }
   var isOrgExist  ;
    if(searchInfo.isOrgExist && searchInfo.isOrgExist != "" &&  searchInfo.isOrgExist != "undefined" ){
        // isOrgExist  = searchInfo.isOrgExist ;
        searchStr2 +=",isOrgExist="+searchInfo.isOrgExist ;
    }
    var tableOptions = $("#dataAppTable").bootstrapTable('getOptions', null);
    searchStr2 += ',pageNo=' + tableOptions.pageNumber + ',pageSize=' + tableOptions.pageSize

    console.log(searchStr2);
    window.location.href = basePath+"bizApp/editChlidDocBizAppPage?"+"t=" +new Date().getTime()+
    "&bizName="+$("#thirdBizName").val()+"&orgName="+$("#thirdOrgName").val()+"&docName="+$("#thirdDocName").val()+"&isvName="+$("#thirdIsvName").val()+"&appid="+(selectedAppRow?selectedAppRow.appid:appid)+"&id="+selectedRow.id+
        "&searchStr="+searchStr+"&searchStr2="+searchStr2;
}